package com.example.mykotlin.base.interceptor

import com.example.mykotlin.base.util.tryOnly
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class RequestInfoInterceptor : HandlerInterceptor {

    companion object {
        val REQUEST_INFO = ThreadLocal<Triple<String, String, String>>()
    }

    fun getIpAddress(request: HttpServletRequest): String {
        var ip = ""
        tryOnly {
            ip = request.remoteAddr ?: ""
            if (ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
                ip = request.getHeader("Proxy-Client-IP") ?: ""
            }
            if (ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
                ip = request.getHeader("WL-Proxy-Client-IP") ?: ""
            }
            if (ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
                ip = request.getHeader("HTTP_CLIENT_IP") ?: ""
            }
            if (ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR") ?: ""
            }
            if (ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
                ip = request.getHeader("x-forwarded-for") ?: ""
            }
        }
        return ip
    }

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        REQUEST_INFO.set(Triple(getIpAddress(request), request.requestURI, request.method))
        return true
    }

    override fun afterCompletion(
        request: HttpServletRequest, response: HttpServletResponse, handler: Any, ex: java.lang.Exception?
    ) {
        REQUEST_INFO.remove()
    }
}